package com.ssy.lingxi.purchase.serviceimpl;

import cn.hutool.core.collection.CollectionUtil;
import com.querydsl.core.BooleanBuilder;
import com.querydsl.core.types.Projections;
import com.querydsl.jpa.impl.JPAQuery;
import com.querydsl.jpa.impl.JPAQueryFactory;
import com.ssy.lingxi.common.constant.CommonConstant;
import com.ssy.lingxi.common.constant.basic.EnableDisableStatus;
import com.ssy.lingxi.common.exception.BusinessException;
import com.ssy.lingxi.common.model.dto.UserLoginCacheDTO;
import com.ssy.lingxi.common.response.PageData;
import com.ssy.lingxi.common.response.ResponseCode;
import com.ssy.lingxi.common.response.Wrapper;
import com.ssy.lingxi.message.api.constant.MessageTemplateCode;
import com.ssy.lingxi.message.api.feign.SystemMessageControllerFeign;
import com.ssy.lingxi.message.api.vo.request.SystemMessageRequest;
import com.ssy.lingxi.purchase.api.common.OrderConstant;
import com.ssy.lingxi.purchase.api.common.PurchaseInquiryConstant;
import com.ssy.lingxi.purchase.api.dto.request.*;
import com.ssy.lingxi.purchase.api.dto.request.purchase.*;
import com.ssy.lingxi.purchase.api.dto.response.BiddingExternalWorkStateEnumResponse;
import com.ssy.lingxi.purchase.api.dto.response.CountryAreaResponse;
import com.ssy.lingxi.purchase.api.dto.response.purchase.*;
import com.ssy.lingxi.purchase.api.enums.purchase.*;
import com.ssy.lingxi.purchase.entity.purchaseinquiry.PurchaseInquiry;
import com.ssy.lingxi.purchase.entity.purchaseinquiry.PurchaseInquiryProduct;
import com.ssy.lingxi.purchase.entity.purchaseinquiry.QDemandMember;
import com.ssy.lingxi.purchase.entity.purchaseinquiry.QPurchaseInquiry;
import com.ssy.lingxi.purchase.entity.quotedprice.*;
import com.ssy.lingxi.purchase.repository.*;
import com.ssy.lingxi.purchase.service.QuotedPriceService;
import com.ssy.lingxi.purchase.utils.PurchaseUtils;
import com.ssy.lingxi.report.api.enums.ConfirmDemandQuotationOperateTypeEnum;
import com.ssy.lingxi.report.api.enums.DemandQuotationOperateTypeEnum;
import com.ssy.lingxi.report.api.enums.OperateDataSourceEnum;
import com.ssy.lingxi.workflow.api.model.contant.ProcessEnum;
import com.ssy.lingxi.workflow.api.model.vo.response.SimpleTaskCompleteVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.persistence.criteria.Predicate;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 采购报价业务处理
 *
 * @author wrc
 * @date 2021/1/26
 */
@Slf4j
@Service
public class QuotedPriceServiceImpl extends BasePurchaseInquiry implements QuotedPriceService {

    @Resource
    PurchaseInquiryRepository purchaseInquiryRepository;
    @Resource
    PurchaseInquiryProductRepository purchaseInquiryProductRepository;
    @Resource
    QuotedPriceRepository quotedPriceRepository;
    @Resource
    QuotedPriceDetailsRepository quotedPriceDetailsRepository;
    @Resource
    InteriorQuotedPriceLogRepository interiorQuotedPriceLogRepository;
    @Resource
    SystemMessageControllerFeign systemMessageControllerFeign;
    @Resource
    JPAQueryFactory queryFactory;
    @Resource
    QuotedPriceTurnRepository quotedPriceTurnRepository;
    @Resource
    private InteriorConfirmQuotedPriceLogRepository interiorConfirmQuotedPriceLogRepository;

    /**
     * 采购报价-采购需求单查询
     */
    @Override
    public Wrapper<PageData<PurchaseInquiryListResponse>> purchaseInquiryList(PurchaseInquiryListRequest request, UserLoginCacheDTO sysUser) {
        List<PurchaseInquiryListResponse> responses;
        QPurchaseInquiry qPurchaseInquiry = QPurchaseInquiry.purchaseInquiry;
        QDemandMember qDemandMember = QDemandMember.demandMember;
        // 定于获取条件
        BooleanBuilder predicates = new BooleanBuilder();
        predicates.and(qPurchaseInquiry.type.in(PurchaseInquiryConstant.type.SYSTEM_MATCHING, PurchaseInquiryConstant.type.INVITATION));
        predicates.and(qPurchaseInquiry.offerEndTime.goe(System.currentTimeMillis()));
        predicates.and(qPurchaseInquiry.externalState.in(PurchaseInquiryListExternalWorkStateEnum.STAY_SUBMIT_OFFER.getState(), PurchaseInquiryListExternalWorkStateEnum.LAUNCH_NEXT_TURN.getState()));
        predicates.and(qDemandMember.memberId.eq(sysUser.getMemberId()));
        predicates.and(qDemandMember.roleId.eq(sysUser.getMemberRoleId()));
        if (StringUtils.hasLength(request.getMemberName())) {
            predicates.and(qPurchaseInquiry.memberName.like("%" + request.getMemberName() + "%"));
        }
        if (null != request.getStartTime()) {
            predicates.and(qPurchaseInquiry.createTime.goe(request.getStartTime()));
        }
        if (null != request.getEndTime()) {
            predicates.and(qPurchaseInquiry.createTime.loe(request.getEndTime()));
        }
        if (StringUtils.hasLength(request.getDetails())) {
            predicates.and(qPurchaseInquiry.details.like("%" + request.getDetails() + "%"));
        }
        if (StringUtils.hasLength(request.getPurchaseInquiryNo())) {
            predicates.and(qPurchaseInquiry.purchaseInquiryNo.like("%" + request.getPurchaseInquiryNo() + "%"));
        }
        JPAQuery<PurchaseInquiryListResponse> query = queryFactory.select(Projections.bean(PurchaseInquiryListResponse.class,
                qPurchaseInquiry.deliveryTime,
                qPurchaseInquiry.purchaseInquiryNo,
                qPurchaseInquiry.offerEndTime,
                qPurchaseInquiry.id,
                qPurchaseInquiry.memberRoleId,
                qPurchaseInquiry.memberName,
                qPurchaseInquiry.memberId,
                qPurchaseInquiry.externalState,
                qPurchaseInquiry.details,
                qPurchaseInquiry.turn,
                qPurchaseInquiry.createTime))
                .from(qPurchaseInquiry)
                .leftJoin(qDemandMember)
                .on(qPurchaseInquiry.id.eq(qDemandMember.purchaseInquiryId))
                .where(predicates);
        long totalCount = query.fetchCount();
        responses = query.orderBy(qPurchaseInquiry.updateTime.desc())
                .offset((long) request.getCurrent() * request.getPageSize())
                .limit(request.getPageSize())
                .fetch();
        if (0 < totalCount) {
            responses.forEach(v -> {
                v.setExternalStateName(PurchaseInquiryListExternalWorkStateEnum.getName(v.getExternalState()));
            });
            //查询当前用户是否已经报价
            List<QuotedPrice> quotedPrices = quotedPriceRepository.findAllByPurchaseInquiryIdInAndCreateMemberIdAndCreateMemberRoleId(responses.stream().map(PurchaseInquiryListResponse::getId).collect(Collectors.toSet()), sysUser.getMemberId(), sysUser.getMemberRoleId());
            if (!CollectionUtils.isEmpty(quotedPrices)) {
                Map<Long, List<QuotedPrice>> collect = quotedPrices.stream().collect(Collectors.groupingBy(QuotedPrice::getPurchaseInquiryId));
                for (PurchaseInquiryListResponse purchaseInquiry : responses) {
                    List<QuotedPrice> quotedPriceList = collect.get(purchaseInquiry.getId());
                    if (CollectionUtils.isEmpty(quotedPriceList)) {
                        purchaseInquiry.setIsQuotedPrice(CommonConstant.State.STATE_STOP);
                        continue;
                    }
                    //查询当前轮次的报价单
                    List<QuotedPrice> quotedPriceTurnList = quotedPriceList.stream().filter(quotedPrice -> quotedPrice.getTurn().equals(purchaseInquiry.getTurn())).collect(Collectors.toList());
                    //未报价
                    if (CollectionUtils.isEmpty(quotedPriceTurnList)) {
                        purchaseInquiry.setIsQuotedPrice(CommonConstant.State.STATE_STOP);
                    } else {
                        purchaseInquiry.setIsQuotedPrice(CommonConstant.State.STATE_START);
                    }
                }
            } else {
                responses.forEach(purchaseInquiry -> {
                    purchaseInquiry.setIsQuotedPrice(CommonConstant.State.STATE_STOP);
                });
            }
        }
        return Wrapper.success(new PageData<>(totalCount, responses));
    }

    /**
     * 需求单报价 - 采购需求单查询 - 采购需求单详情
     */
    @Override
    public Wrapper<PurchaseInquiryDetailsResponse> purchaseInquiryDetails(BaseDetailsRequest request, UserLoginCacheDTO sysUser) {
        //获取需求单
        PurchaseInquiry purchaseInquiry;
        if (null != request.getId()) {
            purchaseInquiry = purchaseInquiryRepository.findById(request.getId()).orElse(null);
        } else {
            purchaseInquiry = purchaseInquiryRepository.findByPurchaseInquiryNo(request.getNumber());
        }
        if (ObjectUtils.isEmpty(purchaseInquiry)) {
            return Wrapper.fail(ResponseCode.RECORDS_DON_T_EXIST);
        }

        //封装需求单
        PurchaseInquiryDetailsResponse response = new PurchaseInquiryDetailsResponse();
        BeanUtils.copyProperties(purchaseInquiry, response);
        response.setAreas(purchaseInquiry.getAreas().stream().map(temp -> {
            CountryAreaResponse countryArea = new CountryAreaResponse();
            BeanUtils.copyProperties(temp, countryArea);
            return countryArea;
        }).collect(Collectors.toList()));
        response.setIsAreas(OrderConstant.State.START.equals(purchaseInquiry.getIsAreas()));

        //获取报价单
        QuotedPrice quotedPrice = quotedPriceRepository.findByPurchaseInquiryIdAndCreateMemberIdAndCreateMemberRoleId(purchaseInquiry.getId(), sysUser.getMemberId(), sysUser.getMemberRoleId());
        if (quotedPrice != null) {
            //获取报价单轮次
            List<QuotedPriceTurn> quotedPriceTurnList = quotedPriceTurnRepository.findAllByQuotedPriceId(quotedPrice.getId(), Sort.by("id"));
            response.setQuotedPriceTurnList(
                    quotedPriceTurnList.stream().map(a -> {
                        QuotedPriceTurnResp quotedPriceTurnResp = new QuotedPriceTurnResp();
                        BeanUtils.copyProperties(a, quotedPriceTurnResp);
                        return quotedPriceTurnResp;
                    }).collect(Collectors.toList())
            );
        }

        //返回当前报价单的已报价轮次
        response.setTurn(ObjectUtils.isEmpty(quotedPrice) ? null : quotedPrice.getTurn());
        response.setQuotedPriceId(ObjectUtils.isEmpty(quotedPrice) ? null : quotedPrice.getId());
        //查询采购物料
        List<PurchaseInquiryProduct> products = purchaseInquiryProductRepository.findAllByPurchaseInquiryId(purchaseInquiry.getId());
        List<PurchaseInquiryProductRequest> productRequests = products.stream().map(temp -> {
            PurchaseInquiryProductRequest productRequest = new PurchaseInquiryProductRequest();
            BeanUtils.copyProperties(temp, productRequest);
            return productRequest;
        }).collect(Collectors.toList());
        response.setMateriels(productRequests);
        //查询需求对接会员列表
        if (!OrderConstant.DockingType.PLATFORM_DOOR.equals(purchaseInquiry.getType())) {
            response.setDemandMembers(getDemandMembers(purchaseInquiry.getId()));
        }
        //查询外部操作记录
        response.setExternalLogs(getExternalLog(purchaseInquiry.getId()));

        //内外部状态name
        response.setExternalStateName(PurchaseInquiryListExternalWorkStateEnum.getName(purchaseInquiry.getExternalState()));
        response.setInteriorStateName(PurchaseInquiryListInteriorWorkStateEnum.getName(purchaseInquiry.getInteriorState()));
        Long roleId = quotedPrice == null ? sysUser.getMemberRoleId() : quotedPrice.getCreateMemberRoleId();
        //查询外部流转状态
        response.setExternalLogStates(getLogStateResponse(ProcessEnum.PURCHASE_INQUIRY_OUTER_VERIFY.getCode(), purchaseInquiry.getExternalNextStep(), Collections.singletonList(roleId), purchaseInquiry.getCreateMemberRoleId()));
        //查询报价附件
        if (quotedPrice != null) {
            response.setTransactionUurls(quotedPrice.getEnclosureUrls());
        }
        return Wrapper.success(response);
    }

    /**
     * 采购询价-采购物料-分页查询
     */
    @Override
    public Wrapper<PageData<PurchaseInquiryProductRequest>> purchaseInquiryProductlist(BaseDetailsRequest request) {
        PurchaseInquiry purchaseInquiry;
        if (null != request.getId()) {
            purchaseInquiry = purchaseInquiryRepository.findById(request.getId()).orElse(null);
        } else {
            purchaseInquiry = purchaseInquiryRepository.findByPurchaseInquiryNo(request.getNumber());
        }
        if (ObjectUtils.isEmpty(purchaseInquiry)) {
            return Wrapper.fail(ResponseCode.RECORDS_DON_T_EXIST);
        }
        PurchaseInquiryProduct product = new PurchaseInquiryProduct();
        product.setPurchaseInquiryId(purchaseInquiry.getId());
        //查询采购物料
        Page<PurchaseInquiryProduct> purchaseInquiryProducts = purchaseInquiryProductRepository.findAll(Example.of(product), PageRequest.of(request.getCurrent(), request.getPageSize(), Sort.by("id").ascending()));
        if (purchaseInquiryProducts.getTotalElements() == 0) {
            return Wrapper.success(new PageData<>(0L, new ArrayList<>()));
        }
        List<PurchaseInquiryProductRequest> productRequests = purchaseInquiryProducts.stream().map(temp -> {
            PurchaseInquiryProductRequest productRequest = new PurchaseInquiryProductRequest();
            BeanUtils.copyProperties(temp, productRequest);
            productRequest.setUrls(temp.getUrls());
            return productRequest;
        }).collect(Collectors.toList());
        return Wrapper.success(new PageData<>(purchaseInquiryProducts.getTotalElements(), productRequests));
    }

    /**
     * 需求单报价
     * 说明: 采购商发布需求单并平台审核通过后, 供应商可以对该需求单进行报价, 同一个会员的供应商且每一轮只可报价一次.
     * 无论供应商报价多少轮, 该供应商对应生成的报价单始终只有一条, 只是报价单详情内的轮次会有不同变化
     */
    @Transactional
    @Override
    public Wrapper<?> quotedPriceAdd(QuotedPriceAddRequest request, UserLoginCacheDTO user) {
        //获取需求单
        PurchaseInquiry purchaseInquiry = purchaseInquiryRepository.findById(request.getPurchaseInquiryId()).orElse(null);
        if (null == purchaseInquiry) {
            return Wrapper.fail(ResponseCode.RECORDS_DON_T_EXIST);
        }

        //获取需求单物料
        List<PurchaseInquiryProduct> purchaseInquiryProducts = purchaseInquiryProductRepository.findAllByPurchaseInquiryId(request.getPurchaseInquiryId());
        if (CollectionUtils.isEmpty(purchaseInquiryProducts)) {
            return Wrapper.fail(ResponseCode.RECORDS_DON_T_EXIST);
        }

        //根据当前供应商和需求单, 获取对应的报价单
        QuotedPrice quotedPrice = quotedPriceRepository.findByPurchaseInquiryIdAndCreateMemberIdAndCreateMemberRoleId(
                request.getPurchaseInquiryId(), user.getMemberId(), user.getMemberRoleId()
        );

        //判断报价单是否为null
        if (quotedPrice == null) {
            //如果供应商在需求单第一轮的时候未报价, 那后续几轮是不能报价的
            if (purchaseInquiry.getTurn() > 1) {
                return Wrapper.fail(ResponseCode.PURCHASE_QUOTE_MUST_COMPLETE_THE_FIRST_ROUND_OF_QUOTATIONS);
            }

            //新增报价单
            quotedPrice = new QuotedPrice();
            quotedPrice.setPurchaseInquiryId(purchaseInquiry.getId());
            quotedPrice.setDetails(purchaseInquiry.getDetails());
            quotedPrice.setCount(purchaseInquiry.getCount());
            quotedPrice.setQuotedDetails(request.getQuotedDetails());
            quotedPrice.setEnclosureUrls(request.getEnclosureUrls());
            quotedPrice.setQuotedPriceNo(PurchaseUtils.randomUniqueNumber("BJ"));
            quotedPrice.setOfferEndTime(purchaseInquiry.getOfferEndTime());
            quotedPrice.setMemberRoleId(purchaseInquiry.getCreateMemberRoleId());
            quotedPrice.setMemberName(purchaseInquiry.getCreateMemberName());
            quotedPrice.setMemberId(purchaseInquiry.getCreateMemberId());
            quotedPrice.setPurchaseInquiryNo(purchaseInquiry.getPurchaseInquiryNo());
            quotedPrice.setCreateMemberId(user.getMemberId());
            quotedPrice.setCreateMemberName(user.getCompany());
            quotedPrice.setCreateMemberRoleId(user.getMemberRoleId());
            quotedPrice.setCreateTime(System.currentTimeMillis());
            quotedPrice.setUpdateTime(System.currentTimeMillis());
            quotedPrice.setIsDecrypt(OrderConstant.State.START.equals(purchaseInquiry.getPriceContrast()) ? OrderConstant.State.STOP : OrderConstant.State.START);
            quotedPrice.setDeliveryTime(purchaseInquiry.getDeliveryTime());
            quotedPrice.setTel(request.getTel());
            quotedPrice.setTelPrefix(request.getTelPrefix());
            quotedPrice.setContacts(request.getContacts());
            quotedPrice.setTurn(purchaseInquiry.getTurn());
            quotedPrice.setExternalTaskId(purchaseInquiry.getExternalTaskId());
            quotedPrice.setExternalNextStep(purchaseInquiry.getExternalNextStep());
            quotedPrice.setExternalState(purchaseInquiry.getExternalState());
            quotedPriceRepository.saveAndFlush(quotedPrice);
        } else {
            //需求单的每一轮中只允许同一会员内的供应商报价一次，不可重复报价
            if (purchaseInquiry.getTurn().equals(quotedPrice.getTurn())) {
                return Wrapper.fail(ResponseCode.PURCHASE_QUOTE_ONLY_FINISH_ONE);
            }

            //更新报价单: 当前报价轮次、报价单摘要、联系电话、联系电话前缀ID、联系人、修改时间
            quotedPrice.setTurn(purchaseInquiry.getTurn());
            quotedPrice.setQuotedDetails(request.getQuotedDetails());
            quotedPrice.setTel(request.getTel());
            quotedPrice.setTelPrefix(request.getTelPrefix());
            quotedPrice.setContacts(request.getContacts());
            quotedPrice.setUpdateTime(System.currentTimeMillis());
            quotedPriceRepository.saveAndFlush(quotedPrice);
        }

        //新增报价单轮次
        QuotedPriceTurn quotedPriceTurn = new QuotedPriceTurn();
        quotedPriceTurn.setPurchaseInquiryId(purchaseInquiry.getId());
        quotedPriceTurn.setQuotedPriceId(quotedPrice.getId());
        quotedPriceTurn.setTurn(quotedPrice.getTurn());
        quotedPriceTurn.setDeliveryDetails(request.getDeliveryDetails());
        quotedPriceTurn.setPayDetails(request.getPayDetails());
        quotedPriceTurn.setTaxes(request.getTaxes());
        quotedPriceTurn.setLogistics(request.getLogistics());
        quotedPriceTurn.setPackRequire(request.getPackRequire());
        quotedPriceTurn.setOtherRequire(request.getOtherRequire());
        quotedPriceTurn.setEnclosureUrls(request.getEnclosureUrls());
        quotedPriceTurn.setQuotedDetails(request.getQuotedDetails());
        quotedPriceTurn.setContacts(quotedPrice.getContacts());
        quotedPriceTurn.setTel(quotedPrice.getTel());
        quotedPriceTurn.setQuotedPriceNo(quotedPrice.getQuotedPriceNo());
        quotedPriceTurn.setTradeTime(quotedPrice.getUpdateTime());
        quotedPriceTurnRepository.saveAndFlush(quotedPriceTurn);

        //对需求单的物料明细按货号ID进行分组
        Map<Long, PurchaseInquiryProduct> collect = purchaseInquiryProducts.stream().collect(Collectors.toMap(
                PurchaseInquiryProduct::getGoodsId, quotedPriceDetailsRequest -> quotedPriceDetailsRequest
        ));
        //批量新增报价单物料详情。(报价单的每一轮次的物料信息都是一样的，不过关联的商品会不同，所以报价单的物料详情会根据轮次字段来区分)
        QuotedPrice finalQuotedPrice = quotedPrice;
        List<QuotedPriceDetails> quotedPriceDetailsList = request.getDetailss().stream().map(details -> {
            QuotedPriceDetails quotedPriceDetails = new QuotedPriceDetails();
            BeanUtils.copyProperties(details, quotedPriceDetails);


            PurchaseInquiryProduct purchaseInquiryProduct = collect.get(details.getGoodsId());
            quotedPriceDetails.setProductId(details.getProductId());
            quotedPriceDetails.setTurn(purchaseInquiry.getTurn());
            quotedPriceDetails.setUnit(purchaseInquiryProduct.getUnit());
            quotedPriceDetails.setTaxPrice(BigDecimal.valueOf(details.getTaxUnitPrice() * purchaseInquiryProduct.getPurchaseCount()).setScale(2, RoundingMode.HALF_UP).doubleValue());
            quotedPriceDetails.setPurchaseCount(purchaseInquiryProduct.getPurchaseCount());
            quotedPriceDetails.setTaxProbability(details.getTaxProbability());
            quotedPriceDetails.setPurchaseInquiryDetailsId(details.getPurchaseInquiryDetailsId());
            quotedPriceDetails.setTaxUnitPrice(details.getTaxUnitPrice());
            quotedPriceDetails.setProductName(details.getProductName());
            quotedPriceDetails.setNumber(purchaseInquiryProduct.getNumber());
            quotedPriceDetails.setName(purchaseInquiryProduct.getName());
            quotedPriceDetails.setModel(purchaseInquiryProduct.getModel());
            quotedPriceDetails.setIsTax(details.getIsTax());
            quotedPriceDetails.setEnclosureUrls(details.getEnclosureUrls());
            quotedPriceDetails.setGoodsId(details.getGoodsId());
            quotedPriceDetails.setCategory(purchaseInquiryProduct.getCategory());
            quotedPriceDetails.setBrand(purchaseInquiryProduct.getBrand());
            quotedPriceDetails.setProductId(details.getProductId());
            quotedPriceDetails.setUnit(purchaseInquiryProduct.getUnit());
            quotedPriceDetails.setQuotedPriceId(finalQuotedPrice.getId());
            quotedPriceDetails.setProductAttributeJson(details.getProductAttributeJson());
            quotedPriceDetails.setImgUrl(details.getImgUrl());
            quotedPriceDetails.setProductBrand(details.getProductBrand());
            return quotedPriceDetails;
        }).collect(Collectors.toList());
        quotedPriceDetailsRepository.saveAll(quotedPriceDetailsList);

        //获取报价总金额
        quotedPrice.setSumPrice(
                BigDecimal.valueOf(
                        quotedPriceDetailsList.stream().mapToDouble(QuotedPriceDetails::getTaxPrice).sum()
                ).setScale(2, RoundingMode.HALF_UP).doubleValue()
        );

        //执行采购报价内部工作流, 更新报价单工作流信息
        Wrapper<SimpleTaskCompleteVO> taskResult = startWork(user, quotedPrice.getId(), ProcessEnum.PURCHASE_OFFER_INNER_VERIFY.getCode());
        if (ResponseCode.SUCCESS.getCode() != taskResult.getCode()) {
            log.error("请求工作流服务失败:{}", taskResult.getMessage());
            throw new BusinessException(ResponseCode.SERVICE_WORKFLOW_ERROR);
        }
        quotedPrice.setInteriorTaskId(taskResult.getData().getTaskId());
        quotedPrice.setInteriorState(taskResult.getData().getStatus());
        quotedPrice.setInteriorNextStep(taskResult.getData().getStep());
        quotedPriceRepository.saveAndFlush(quotedPrice);

        //记录需求报价单内部操作记录、增加扣减记录操作数据记录、发消息
        saveInteriorLog(user, QuoteOperationEnum.ADD_QUOTE.getCHName(), taskResult.getData().getStep(), taskResult.getData().getStatus(), quotedPrice.getId(), "");
        reduceCount(quotedPrice.getDetails(), quotedPrice.getCreateMemberId(), quotedPrice.getCreateMemberRoleId(), OperateDataSourceEnum.PURCHASE_QUOTED_PRICE.getCode(), 1L, DemandQuotationOperateTypeEnum.TO_BE_VALIFY_COMMIT.getCode(), 0L, 0);
        sendSystemMessage(quotedPrice, MessageTemplateCode.demand_quotation_wait_audit);
        return Wrapper.success();
    }

    /**
     * 修改报价单
     */
    @Transactional
    @Override
    public Wrapper<?> quotedPriceUpdate(QuotedPriceUpdateRequest request, UserLoginCacheDTO sysUser) {
        //获取报价单
        QuotedPrice quotedPrice = quotedPriceRepository.findById(request.getId()).orElse(null);
        if (ObjectUtils.isEmpty(quotedPrice)) {
            return Wrapper.fail(ResponseCode.RECORDS_DON_T_EXIST);
        }

        //更新报价单: 报价单摘要、联系电话、联系电话前缀ID、联系人、附件、修改时间
        quotedPrice.setQuotedDetails(request.getQuotedDetails());
        quotedPrice.setTel(request.getTel());
        quotedPrice.setTelPrefix(request.getTelPrefix());
        quotedPrice.setContacts(request.getContacts());
        quotedPrice.setEnclosureUrls(request.getEnclosureUrls());
        quotedPrice.setUpdateTime(System.currentTimeMillis());
        //更新报价单物料
        Map<Long, QuotedPriceDetailsRequest> collect = request.getDetailss().stream().collect(Collectors.toMap(
                QuotedPriceDetailsRequest::getPurchaseInquiryDetailsId, QuotedPriceDetailsRequest -> QuotedPriceDetailsRequest
        ));
        List<QuotedPriceDetails> quotedPriceDetailss = quotedPriceDetailsRepository.findAllByQuotedPriceId(quotedPrice.getId());
        quotedPriceDetailss.forEach(quotedPriceDetails -> {
            QuotedPriceDetailsRequest detailsRequest = collect.get(quotedPriceDetails.getPurchaseInquiryDetailsId());

            //如果为null的说明是非同一轮的
            if (detailsRequest != null) {
                Double purchaseCount = quotedPriceDetails.getPurchaseCount();
                Double taxUnitPrice = detailsRequest.getTaxUnitPrice();
                quotedPriceDetails.setTaxPrice(BigDecimal.valueOf(taxUnitPrice * purchaseCount).setScale(2, RoundingMode.HALF_UP).doubleValue());
                quotedPriceDetails.setTaxUnitPrice(taxUnitPrice);
                quotedPriceDetails.setTaxProbability(detailsRequest.getTaxProbability());
                quotedPriceDetails.setProductAttributeJson(quotedPriceDetails.getProductAttributeJson());
                quotedPriceDetails.setIsTax(detailsRequest.getIsTax());
                quotedPriceDetails.setEnclosureUrls(detailsRequest.getEnclosureUrls());
            }
        });
        quotedPriceDetailsRepository.saveAll(quotedPriceDetailss);

        //根据报价单ID和报价单当前轮次来获取报价单轮次(正常是返回一条的, 返回多条说明有问题)
        QuotedPriceTurn quotedPriceTurn = quotedPriceTurnRepository.findByQuotedPriceIdAndTurn(quotedPrice.getId(), quotedPrice.getTurn());
        quotedPriceTurn.setDeliveryDetails(request.getDeliveryDetails());
        quotedPriceTurn.setPayDetails(request.getPayDetails());
        quotedPriceTurn.setTaxes(request.getTaxes());
        quotedPriceTurn.setLogistics(request.getLogistics());
        quotedPriceTurn.setPackRequire(request.getPackRequire());
        quotedPriceTurn.setOtherRequire(request.getOtherRequire());
        quotedPriceTurn.setEnclosureUrls(request.getEnclosureUrls());
        quotedPriceTurn.setQuotedDetails(request.getQuotedDetails());
        quotedPriceTurn.setContacts(quotedPrice.getContacts());
        quotedPriceTurn.setTel(quotedPrice.getTel());
        quotedPriceTurn.setQuotedPriceNo(quotedPrice.getQuotedPriceNo());
        quotedPriceTurn.setTradeTime(quotedPrice.getUpdateTime());
        quotedPriceTurnRepository.saveAndFlush(quotedPriceTurn);

        //执行内部工作流
        Wrapper<SimpleTaskCompleteVO> taskResult = startWork(sysUser, quotedPrice.getId(), ProcessEnum.PURCHASE_OFFER_INNER_VERIFY.getCode());
        if (ResponseCode.SUCCESS.getCode() != taskResult.getCode()) {
            return taskResult;
        }
        quotedPrice.setInteriorTaskId(taskResult.getData().getTaskId());
        quotedPrice.setInteriorState(taskResult.getData().getStatus());
        quotedPrice.setInteriorNextStep(taskResult.getData().getStep());

        //更新报价单
        quotedPriceRepository.saveAndFlush(quotedPrice);

        saveInteriorLog(sysUser, QuoteOperationEnum.UPDATE_QUOTE.getCHName(), quotedPrice.getInteriorState(), quotedPrice.getInteriorState(), quotedPrice.getId(), "");
        return Wrapper.success();
    }

    /**
     * 删除报价单
     */
    @Transactional
    @Override
    public Wrapper quotedPriceDelete(BaseRequest request, UserLoginCacheDTO sysUser) {
        //删除报价单，待提交审核且从未提交过审核的报价单可以删除
        QuotedPrice quotedPrice = quotedPriceRepository.findById(request.getId()).orElse(null);
        if (ObjectUtils.isEmpty(quotedPrice)) {
            return Wrapper.fail(ResponseCode.RECORDS_DON_T_EXIST);
        }
        if (!QuotedPriceInteriorWorkStateEnum.STAY_SUBMIT_EXAMINE.getState().equals(quotedPrice.getInteriorState())) {
            return Wrapper.fail(ResponseCode.PURCHASE_QUOTE_STATUS_MISMATCH);
        }

        //若非第一轮报价，则不予许删除报价单
        if (quotedPrice.getTurn() > 1) {
            return Wrapper.fail("当前需求单已报过价，不可删除报价单！");
        }
        quotedPriceRepository.deleteById(request.getId());
        quotedPriceTurnRepository.deleteAllByQuotedPriceId(request.getId());
        return Wrapper.success();
    }

    /**
     * 批量删除报价单
     */
    @Transactional
    @Override
    public Wrapper quotedPriceDeleteBatch(BaseAllRequest request, UserLoginCacheDTO sysUser) {
        List<QuotedPrice> quotedPrices = quotedPriceRepository.findAllById(request.getIds());
        if (CollectionUtils.isEmpty(quotedPrices)) {
            return Wrapper.fail(ResponseCode.RECORDS_DON_T_EXIST);
        }
        for (QuotedPrice quotedPrice : quotedPrices) {
            if (!QuotedPriceInteriorWorkStateEnum.STAY_SUBMIT_EXAMINE.getState().equals(quotedPrice.getInteriorState())) {
                return Wrapper.fail(ResponseCode.PURCHASE_QUOTE_STATUS_MISMATCH);
            }
            //若非第一轮报价，则不予许删除报价单
            if (quotedPrice.getTurn() > 1) {
                return Wrapper.fail("当前需求单已报过价，不可删除报价单！");
            }
        }
        quotedPriceRepository.deleteAll(quotedPrices);
        quotedPriceTurnRepository.deleteAllByQuotedPriceIdIn(request.getIds());
        return Wrapper.success();
    }

    /**
     * 采购报价单列表查询
     */
    @Override
    public Wrapper<PageData<QuotedPriceListResponse>> quotedPriceList(QuotedPriceListRequest request, UserLoginCacheDTO sysUser) {
        return getQuotedPriceList(request, sysUser, QuotedPriceQueryEnum.PURCHASE_INQUIRY_LIST.getType());
    }

    /**
     * 报价单详情
     */
    @Override
    public Wrapper<QuotedPriceDetailsResponse> quotedPriceDetails(BaseDetailsRequest request, UserLoginCacheDTO sysUser) {
        QuotedPrice quotedPrice;
        if (!StringUtils.hasLength(request.getNumber())) {
            quotedPrice = quotedPriceRepository.findByIdAndCreateMemberIdAndCreateMemberRoleId(request.getId(), sysUser.getMemberId(), sysUser.getMemberRoleId());
        } else {
            quotedPrice = quotedPriceRepository.findByQuotedPriceNoAndCreateMemberIdAndCreateMemberRoleId(request.getNumber(), sysUser.getMemberId(), sysUser.getMemberRoleId());
        }
        if (ObjectUtils.isEmpty(quotedPrice)) {
            return Wrapper.fail(ResponseCode.RECORDS_DON_T_EXIST);
        }
        QuotedPriceDetailsResponse response = new QuotedPriceDetailsResponse();
        BeanUtils.copyProperties(quotedPrice, response);
        //如果外部状态为已完成，设置未中标
        if (quotedPrice.getExternalState() == 99 && quotedPrice.getIsPrize() == null) {
            response.setIsPrize(0);
        }
        List<QuotedPriceDetails> quotedPriceDetails = quotedPriceDetailsRepository.findAllByQuotedPriceId(quotedPrice.getId());
        response.setQuotedPriceProducts(intoQuotedPriceDetailsResponse(quotedPriceDetails));
        //查询内部流转状态
        response.setInteriorLogStates(logStateInterior(quotedPrice.getCreateMemberId(), ProcessEnum.PURCHASE_OFFER_INNER_VERIFY.getCode(), quotedPrice.getInteriorNextStep()));
        //查询内部操作记录
        List<InteriorPurchaseInquiryLogResponse> quotedPriceInteriorLogs = getQuotedPriceInteriorLog(quotedPrice.getId());
        response.setInteriorLogs(quotedPriceInteriorLogs);
        //获取采购询价实体信息
        PurchaseInquiry purchaseInquiry = purchaseInquiryRepository.findById(quotedPrice.getPurchaseInquiryId()).orElse(null);
        if (purchaseInquiry == null) {
            return Wrapper.fail(ResponseCode.PURCHASE_DATA_RECORDS_DON_T_EXIST);
        }
        //内外部状态name
        response.setExternalStateName(PurchaseInquiryListInteriorWorkStateEnum.getName(purchaseInquiry.getExternalState()));
        //封装数据(key:需求单id,value:需求单externalState)
        //动态获取内部状态name
        response.setInteriorStateName(PurchaseInquiryListExternalWorkStateEnum.getName(quotedPrice.getExternalState()));

        //查询外部操作记录
        response.setExternalLogs(getExternalLog(quotedPrice.getPurchaseInquiryId()));
        //查询外部流转状态
        response.setExternalLogStates(getLogStateResponse(ProcessEnum.PURCHASE_INQUIRY_OUTER_VERIFY.getCode(), quotedPrice.getExternalNextStep(), Collections.singletonList(quotedPrice.getCreateMemberRoleId()), purchaseInquiry.getCreateMemberRoleId()));

        //获取报价单轮次
        List<QuotedPriceTurn> quotedPriceTurnList = quotedPriceTurnRepository.findAllByQuotedPriceId(quotedPrice.getId(), Sort.by("id"));
        response.setQuotedPriceTurnList(
                quotedPriceTurnList.stream().map(a -> {
                    QuotedPriceTurnResp quotedPriceTurnResp = new QuotedPriceTurnResp();
                    BeanUtils.copyProperties(a, quotedPriceTurnResp);
                    return quotedPriceTurnResp;
                }).collect(Collectors.toList())
        );
        return Wrapper.success(response);
    }

    /**
     * 待新增报价单
     */
    @Override
    public Wrapper<PageData<QuotedPriceListResponse>> quotedPriceAddList(QuotedPriceListRequest request, UserLoginCacheDTO sysUser) {
        Wrapper<PageData<QuotedPriceListResponse>> quotedPriceList = getQuotedPriceList(request, sysUser, QuotedPriceQueryEnum.ADD_PURCHASE_INQUIRY_LIST.getType());
        if (ResponseCode.SUCCESS.getCode() == quotedPriceList.getCode() && !CollectionUtils.isEmpty(quotedPriceList.getData().getData())) {
            quotedPriceList.getData().getData().forEach(response -> {
                response.setButton(QuotedPriceInteriorWorkStateEnum.STAY_SUBMIT_EXAMINE.getState().equals(response.getInteriorState()) ? ButtonEnum.SUBMIT_ORDER.getStep() : ButtonEnum.CONFIRM_ORDER.getStep());
            });
        }
        return quotedPriceList;
    }

    /**
     * 采购询价-提交审核采购报价单
     */
    @Transactional
    @Override
    public Wrapper quotedPriceExamine(BaseRequest request, UserLoginCacheDTO sysUser) {
        QuotedPrice quotedPrice = quotedPriceRepository.findById(request.getId()).orElse(null);
        if (ObjectUtils.isEmpty(quotedPrice)) {
            return Wrapper.fail(ResponseCode.RECORDS_DON_T_EXIST);
        }
        if (!QuotedPriceInteriorWorkStateEnum.STAY_SUBMIT_EXAMINE.getState().equals(quotedPrice.getInteriorState())) {
            return Wrapper.fail(ResponseCode.PURCHASE_QUOTE_STATUS_MISMATCH);
        }
        Wrapper<SimpleTaskCompleteVO> taskResult = executeWork(sysUser.getMemberId(), sysUser.getMemberRoleId(), request.getId(), ProcessEnum.PURCHASE_OFFER_INNER_VERIFY.getCode(), quotedPrice.getInteriorNextStep(), quotedPrice.getInteriorTaskId(), OrderConstant.Auditing.DEFAULT);
        if (ResponseCode.SUCCESS.getCode() != taskResult.getCode()) {
            return taskResult;
        }
        quotedPrice.setInteriorTaskId(taskResult.getData().getTaskId());
        quotedPrice.setInteriorState(taskResult.getData().getStatus());
        quotedPrice.setInteriorNextStep(taskResult.getData().getStep());
        quotedPriceRepository.saveAndFlush(quotedPrice);
        reduceCount(quotedPrice.getDetails(), quotedPrice.getCreateMemberId(), quotedPrice.getCreateMemberRoleId(), OperateDataSourceEnum.PURCHASE_QUOTED_PRICE.getCode(), 1L, DemandQuotationOperateTypeEnum.TO_BE_VALIFY_STEP1.getCode(), 1L, DemandQuotationOperateTypeEnum.TO_BE_VALIFY_COMMIT.getCode());
        sendSystemMessage(quotedPrice, MessageTemplateCode.demand_quotation_audit_step_1);
        return Wrapper.success();
    }

    /**
     * 采购询价-提交审核采购报价单批量
     */
    @Transactional
    @Override
    public Wrapper quotedPriceExamineBatch(BaseAllRequest request, UserLoginCacheDTO sysUser) {
        List<QuotedPrice> quotedPrices = quotedPriceRepository.findAllById(request.getIds());
        if (CollectionUtils.isEmpty(quotedPrices)) {
            return Wrapper.fail(ResponseCode.RECORDS_DON_T_EXIST);
        }
        for (QuotedPrice quotedPrice : quotedPrices) {
            if (!QuotedPriceInteriorWorkStateEnum.STAY_SUBMIT_EXAMINE.getState().equals(quotedPrice.getInteriorState())) {
                return Wrapper.fail(ResponseCode.PURCHASE_QUOTE_STATUS_MISMATCH);
            }
            Wrapper<SimpleTaskCompleteVO> taskResult = executeWork(sysUser.getMemberId(), sysUser.getMemberRoleId(), quotedPrice.getId(), ProcessEnum.PURCHASE_OFFER_INNER_VERIFY.getCode(), quotedPrice.getInteriorNextStep(), quotedPrice.getInteriorTaskId(), OrderConstant.Auditing.DEFAULT);
            if (ResponseCode.SUCCESS.getCode() != taskResult.getCode()) {
                throw new RuntimeException(taskResult.getMessage());
            }
            quotedPrice.setInteriorTaskId(taskResult.getData().getTaskId());
            quotedPrice.setInteriorState(taskResult.getData().getStatus());
            quotedPrice.setInteriorNextStep(taskResult.getData().getStep());
            reduceCount(quotedPrice.getDetails(), quotedPrice.getCreateMemberId(), quotedPrice.getCreateMemberRoleId(), OperateDataSourceEnum.PURCHASE_QUOTED_PRICE.getCode(), 1L, DemandQuotationOperateTypeEnum.TO_BE_VALIFY_STEP1.getCode(), 1L, DemandQuotationOperateTypeEnum.TO_BE_VALIFY_COMMIT.getCode());
            sendSystemMessage(quotedPrice, MessageTemplateCode.demand_quotation_audit_step_1);
        }
        quotedPriceRepository.saveAll(quotedPrices);
        return Wrapper.success();
    }

    /**
     * 采购询价-待审核报价单(一级)
     */
    @Override
    public Wrapper<PageData<QuotedPriceListResponse>> quotedPricestayExamineList1(QuotedPriceListRequest request, UserLoginCacheDTO sysUser) {
        return getQuotedPriceList(request, sysUser, QuotedPriceQueryEnum.EXAMINE_PURCHASE_INQUIRY_LIST1.getType());
    }

    /**
     * 采购询价-提交审核采购报价单
     */
    @Transactional
    @Override
    public Wrapper quotedPriceExamine1(BaseExamineRequest request, UserLoginCacheDTO sysUser) {
        QuotedPrice quotedPrice = quotedPriceRepository.findById(request.getId()).orElse(null);
        if (ObjectUtils.isEmpty(quotedPrice)) {
            return Wrapper.fail(ResponseCode.RECORDS_DON_T_EXIST);
        }
        if (!QuotedPriceInteriorWorkStateEnum.STAY_EXAMINE1.getState().equals(quotedPrice.getInteriorState())) {
            return Wrapper.fail(ResponseCode.PURCHASE_QUOTE_STATUS_MISMATCH);
        }
        Wrapper<SimpleTaskCompleteVO> taskResult = executeWork(sysUser.getMemberId(), sysUser.getMemberRoleId(), request.getId(), ProcessEnum.PURCHASE_OFFER_INNER_VERIFY.getCode(), quotedPrice.getInteriorNextStep(), quotedPrice.getInteriorTaskId(), request.getState());
        if (ResponseCode.SUCCESS.getCode() != taskResult.getCode()) {
            throw new RuntimeException(taskResult.getMessage());
        }
        quotedPrice.setInteriorTaskId(taskResult.getData().getTaskId());
        quotedPrice.setInteriorState(taskResult.getData().getStatus());
        quotedPrice.setInteriorNextStep(taskResult.getData().getStep());
        quotedPriceRepository.saveAndFlush(quotedPrice);
        boolean isAuditing = OrderConstant.Auditing.PASS != request.getState();
        saveInteriorLog(sysUser, QuoteOperationEnum.CHECK_QUOTE_1.getCHName(), taskResult.getData().getStep(), taskResult.getData().getStatus(), quotedPrice.getId(), isAuditing ? request.getAuditOpinion() : StatusEnum.AGREE.getCHName());
        if (isAuditing) {
            reduceCount(quotedPrice.getDetails(), quotedPrice.getCreateMemberId(), quotedPrice.getCreateMemberRoleId(), OperateDataSourceEnum.PURCHASE_QUOTED_PRICE.getCode(), 1L, DemandQuotationOperateTypeEnum.TO_BE_VALIFY_COMMIT.getCode(), 1L, DemandQuotationOperateTypeEnum.TO_BE_VALIFY_STEP1.getCode());
            sendSystemMessage(quotedPrice, MessageTemplateCode.demand_quotation_wait_audit);
        } else {
            reduceCount(quotedPrice.getDetails(), quotedPrice.getCreateMemberId(), quotedPrice.getCreateMemberRoleId(), OperateDataSourceEnum.PURCHASE_QUOTED_PRICE.getCode(), 1L, DemandQuotationOperateTypeEnum.TO_BE_VALIFY_STEP2.getCode(), 1L, DemandQuotationOperateTypeEnum.TO_BE_VALIFY_STEP1.getCode());
            sendSystemMessage(quotedPrice, MessageTemplateCode.demand_quotation_audit_step_2);
        }
        return Wrapper.success();
    }

    /**
     * 采购询价-提交审核采购报价单批量(一级)
     */
    @Transactional
    @Override
    public Wrapper quotedPriceExamine1Batch(BaseAllRequest request, UserLoginCacheDTO sysUser) {
        List<QuotedPrice> quotedPrices = quotedPriceRepository.findAllById(request.getIds());
        if (CollectionUtils.isEmpty(quotedPrices)) {
            return Wrapper.fail(ResponseCode.RECORDS_DON_T_EXIST);
        }
        for (QuotedPrice quotedPrice : quotedPrices) {
            if (!QuotedPriceInteriorWorkStateEnum.STAY_EXAMINE1.getState().equals(quotedPrice.getInteriorState())) {
                return Wrapper.fail(ResponseCode.QUOTED_PRICE_STATE_NOT);
            }
            Wrapper<SimpleTaskCompleteVO> taskResult = executeWork(sysUser.getMemberId(), sysUser.getMemberRoleId(), quotedPrice.getId(), ProcessEnum.PURCHASE_OFFER_INNER_VERIFY.getCode(), quotedPrice.getInteriorNextStep(), quotedPrice.getInteriorTaskId(), OrderConstant.Auditing.PASS);
            if (ResponseCode.SUCCESS.getCode() != taskResult.getCode()) {
                throw new RuntimeException(taskResult.getMessage());
            }
            quotedPrice.setInteriorTaskId(taskResult.getData().getTaskId());
            quotedPrice.setInteriorState(taskResult.getData().getStatus());
            quotedPrice.setInteriorNextStep(taskResult.getData().getStep());
            saveInteriorLog(sysUser, QuoteOperationEnum.CHECK_QUOTE_1.getCHName(), taskResult.getData().getStep(), taskResult.getData().getStatus(), quotedPrice.getId(), StatusEnum.AGREE.getCHName());
            reduceCount(quotedPrice.getDetails(), quotedPrice.getCreateMemberId(), quotedPrice.getCreateMemberRoleId(), OperateDataSourceEnum.PURCHASE_QUOTED_PRICE.getCode(), 1L, DemandQuotationOperateTypeEnum.TO_BE_VALIFY_STEP2.getCode(), 1L, DemandQuotationOperateTypeEnum.TO_BE_VALIFY_STEP1.getCode());
            sendSystemMessage(quotedPrice, MessageTemplateCode.demand_quotation_audit_step_2);
        }
        quotedPriceRepository.saveAll(quotedPrices);
        return Wrapper.success();
    }

    /**
     * 采购询价-待审核报价单(二级)
     */
    @Override
    public Wrapper<PageData<QuotedPriceListResponse>> quotedPricestayExamineList2(QuotedPriceListRequest request, UserLoginCacheDTO sysUser) {
        return getQuotedPriceList(request, sysUser, QuotedPriceQueryEnum.EXAMINE_PURCHASE_INQUIRY_LIST2.getType());
    }

    /**
     * 采购询价-提交审核采购报价单二级
     */
    @Transactional
    @Override
    public Wrapper quotedPriceExamine2(BaseExamineRequest request, UserLoginCacheDTO sysUser) {
        QuotedPrice quotedPrice = quotedPriceRepository.findById(request.getId()).orElse(null);
        if (ObjectUtils.isEmpty(quotedPrice)) {
            return Wrapper.fail(ResponseCode.RECORDS_DON_T_EXIST);
        }
        if (!QuotedPriceInteriorWorkStateEnum.STAY_EXAMINE2.getState().equals(quotedPrice.getInteriorState())) {
            return Wrapper.fail(ResponseCode.PURCHASE_QUOTE_STATUS_MISMATCH);
        }
        Wrapper<SimpleTaskCompleteVO> taskResult = executeWork(sysUser.getMemberId(), sysUser.getMemberRoleId(), request.getId(), ProcessEnum.PURCHASE_OFFER_INNER_VERIFY.getCode(), quotedPrice.getInteriorNextStep(), quotedPrice.getInteriorTaskId(), request.getState());
        if (ResponseCode.SUCCESS.getCode() != taskResult.getCode()) {
            throw new RuntimeException(taskResult.getMessage());
        }
        quotedPrice.setInteriorTaskId(taskResult.getData().getTaskId());
        quotedPrice.setInteriorState(taskResult.getData().getStatus());
        quotedPrice.setInteriorNextStep(taskResult.getData().getStep());
        quotedPriceRepository.saveAndFlush(quotedPrice);
        boolean isAuditing = OrderConstant.Auditing.PASS != request.getState();
        saveInteriorLog(sysUser, QuoteOperationEnum.CHECK_QUOTE_2.getCHName(), taskResult.getData().getStep(), taskResult.getData().getStatus(), quotedPrice.getId(), isAuditing ? request.getAuditOpinion() : StatusEnum.AGREE.getCHName());
        if (isAuditing) {
            reduceCount(quotedPrice.getDetails(), quotedPrice.getCreateMemberId(), quotedPrice.getCreateMemberRoleId(), OperateDataSourceEnum.PURCHASE_QUOTED_PRICE.getCode(), 1L, DemandQuotationOperateTypeEnum.TO_BE_VALIFY_COMMIT.getCode(), 1L, DemandQuotationOperateTypeEnum.TO_BE_VALIFY_STEP2.getCode());
            sendSystemMessage(quotedPrice, MessageTemplateCode.demand_quotation_submit);
        } else {
            reduceCount(quotedPrice.getDetails(), quotedPrice.getCreateMemberId(), quotedPrice.getCreateMemberRoleId(), OperateDataSourceEnum.PURCHASE_QUOTED_PRICE.getCode(), 1L, DemandQuotationOperateTypeEnum.TO_BE_COMMIT.getCode(), 1L, DemandQuotationOperateTypeEnum.TO_BE_VALIFY_STEP2.getCode());
            sendSystemMessage(quotedPrice, MessageTemplateCode.demand_quotation_wait_audit);
        }
        return Wrapper.success();
    }

    /**
     * 采购询价-提交审核采购报价单批量二级
     */
    @Transactional
    @Override
    public Wrapper quotedPriceExamine2Batch(BaseAllRequest request, UserLoginCacheDTO sysUser) {
        List<QuotedPrice> quotedPrices = quotedPriceRepository.findAllById(request.getIds());
        if (CollectionUtils.isEmpty(quotedPrices)) {
            return Wrapper.fail(ResponseCode.RECORDS_DON_T_EXIST);
        }
        for (QuotedPrice quotedPrice : quotedPrices) {
            Wrapper<SimpleTaskCompleteVO> taskResult = executeWork(sysUser.getMemberId(), sysUser.getMemberRoleId(), quotedPrice.getId(), ProcessEnum.PURCHASE_OFFER_INNER_VERIFY.getCode(), quotedPrice.getInteriorNextStep(), quotedPrice.getInteriorTaskId(), OrderConstant.Auditing.PASS);
            if (ResponseCode.SUCCESS.getCode() != taskResult.getCode()) {
                throw new RuntimeException(taskResult.getMessage());
            }
            quotedPrice.setInteriorTaskId(taskResult.getData().getTaskId());
            quotedPrice.setInteriorState(taskResult.getData().getStatus());
            quotedPrice.setInteriorNextStep(taskResult.getData().getStep());
            quotedPriceRepository.saveAndFlush(quotedPrice);
            saveInteriorLog(sysUser, QuoteOperationEnum.CHECK_QUOTE_2.getCHName(), taskResult.getData().getStep(), taskResult.getData().getStatus(), quotedPrice.getId(), StatusEnum.AGREE.getCHName());
            reduceCount(quotedPrice.getDetails(), quotedPrice.getCreateMemberId(), quotedPrice.getCreateMemberRoleId(), OperateDataSourceEnum.PURCHASE_QUOTED_PRICE.getCode(), 1L, DemandQuotationOperateTypeEnum.TO_BE_COMMIT.getCode(), 1L, DemandQuotationOperateTypeEnum.TO_BE_VALIFY_STEP2.getCode());
            sendSystemMessage(quotedPrice, MessageTemplateCode.demand_quotation_submit);
        }
        quotedPriceRepository.saveAll(quotedPrices);
        return Wrapper.success();
    }

    /**
     * 采购询价-待提交报价单
     */
    @Override
    public Wrapper<PageData<QuotedPriceListResponse>> quotedPricestayStayCommitList(QuotedPriceListRequest request, UserLoginCacheDTO sysUser) {
        return getQuotedPriceList(request, sysUser, QuotedPriceQueryEnum.SUBMIT_PURCHASE_INQUIRY_LIST.getType());
    }

    /**
     * 采购询价-提交报价单
     */
    @Transactional
    @Override
    public Wrapper quotedPriceStayCommit(BaseRequest request, UserLoginCacheDTO sysUser) {
        QuotedPrice quotedPrice = quotedPriceRepository.findById(request.getId()).orElse(null);
        if (ObjectUtils.isEmpty(quotedPrice)) {
            return Wrapper.fail(ResponseCode.RECORDS_DON_T_EXIST);
        }
        if (!QuotedPriceInteriorWorkStateEnum.STAY_SUBMIT_EXAMINE_QUOTEDPRICE.getState().equals(quotedPrice.getInteriorState())) {
            return Wrapper.fail(ResponseCode.PURCHASE_QUOTE_STATUS_MISMATCH);
        }
        PurchaseInquiry purchaseInquiry = purchaseInquiryRepository.findById(quotedPrice.getPurchaseInquiryId()).orElse(null);
        if (ObjectUtils.isEmpty(purchaseInquiry)) {
            return Wrapper.fail(ResponseCode.RECORDS_DON_T_EXIST);
        }
        if (purchaseInquiry.getOfferEndTime() <= System.currentTimeMillis()) {
            return Wrapper.fail(ResponseCode.PURCHASE_QUOTE_THE_QUOTATION_TIME_FOR_THE_DEMAND_ORDER_HAS_ENDED);
        }
        if (!purchaseInquiry.getTurn().equals(quotedPrice.getTurn())) {
            return Wrapper.fail(ResponseCode.PURCHASE_QUOTE_TIMES_INCOMPATIBLE);
        }

        Wrapper<SimpleTaskCompleteVO> taskResult = executeWork(sysUser.getMemberId(), sysUser.getMemberRoleId(), request.getId(), ProcessEnum.PURCHASE_OFFER_INNER_VERIFY.getCode(), quotedPrice.getInteriorNextStep(), quotedPrice.getInteriorTaskId(), OrderConstant.Auditing.DEFAULT);
        if (ResponseCode.SUCCESS.getCode() != taskResult.getCode()) {
            throw new RuntimeException(taskResult.getMessage());
        }
        quotedPrice.setInteriorTaskId(taskResult.getData().getTaskId());
        quotedPrice.setInteriorState(taskResult.getData().getStatus());
        quotedPrice.setInteriorNextStep(taskResult.getData().getStep());
        saveInteriorLog(sysUser, QuoteOperationEnum.SUBMIT_QUOTE.getCHName(), taskResult.getData().getStep(), taskResult.getData().getStatus(), quotedPrice.getId(), "");
        purchaseInquiry.setCount(null == purchaseInquiry.getCount() ? 1 : purchaseInquiry.getCount() + 1);
        purchaseInquiryRepository.save(purchaseInquiry);
        quotedPriceRepository.saveAndFlush(quotedPrice);
        reduceCount(quotedPrice.getDetails(), quotedPrice.getCreateMemberId(), quotedPrice.getCreateMemberRoleId(), OperateDataSourceEnum.PURCHASE_QUOTED_PRICE.getCode(), 0L, 0, 1L, DemandQuotationOperateTypeEnum.TO_BE_COMMIT.getCode());
//        reduceCount(quotedPrice.getDetails(), quotedPrice.getMemberId(), quotedPrice.getMemberRoleId(), OperateDataSourceEnum.PURCHASE_CONFIRM_QUOTED_PRICE.getCode(), 1L, ConfirmDemandQuotationOperateTypeEnum.TO_BE_VALIFY_COMMIT.getCode(), 0L, 0);
        sendSystemMessagePurchaseInquiry(purchaseInquiry, MessageTemplateCode.confirm_demand_quotation_wait_audit);

        //更新报价单当前轮次的状态为已完成
        QuotedPriceTurn quotedPriceTurn = quotedPriceTurnRepository.findByQuotedPriceIdAndTurn(quotedPrice.getId(), quotedPrice.getTurn());
        quotedPriceTurn.setStatus(EnableDisableStatus.ENABLE.getCode());
        quotedPriceTurnRepository.saveAndFlush(quotedPriceTurn);

        return Wrapper.success();
    }

    /**
     * 采购询价-提交报价单批量
     */
    @Override
    public Wrapper quotedPriceStayCommitBatch(BaseAllRequest request, UserLoginCacheDTO sysUser) {
        List<QuotedPrice> quotedPrices = quotedPriceRepository.findAllById(request.getIds());
        if (CollectionUtils.isEmpty(quotedPrices)) {
            return Wrapper.fail(ResponseCode.RECORDS_DON_T_EXIST);
        }
        List<PurchaseInquiry> purchaseInquirys = purchaseInquiryRepository.findAllById(quotedPrices.stream().map(QuotedPrice::getPurchaseInquiryId).collect(Collectors.toSet()));
        if (CollectionUtils.isEmpty(purchaseInquirys)) {
            return Wrapper.fail(ResponseCode.RECORDS_DON_T_EXIST);
        }
        Map<Long, PurchaseInquiry> collect = purchaseInquirys.stream().collect(Collectors.toMap(PurchaseInquiry::getId, PurchaseInquiry -> PurchaseInquiry));
        List<PurchaseInquiry> list = new ArrayList<>();
        for (QuotedPrice quotedPrice : quotedPrices) {
            if (ObjectUtils.isEmpty(quotedPrice)) {
                return Wrapper.fail(ResponseCode.RECORDS_DON_T_EXIST);
            }
            if (!QuotedPriceInteriorWorkStateEnum.STAY_SUBMIT_EXAMINE_QUOTEDPRICE.getState().equals(quotedPrice.getInteriorState())) {
                return Wrapper.fail(ResponseCode.PURCHASE_QUOTE_STATUS_MISMATCH);
            }
            PurchaseInquiry purchaseInquiry = collect.get(quotedPrice.getPurchaseInquiryId());
            if (ObjectUtils.isEmpty(purchaseInquiry)) {
                return Wrapper.fail(ResponseCode.RECORDS_DON_T_EXIST);
            }
            Wrapper<SimpleTaskCompleteVO> taskResult = executeWork(sysUser.getMemberId(), sysUser.getMemberRoleId(), quotedPrice.getId(), ProcessEnum.PURCHASE_OFFER_INNER_VERIFY.getCode(), quotedPrice.getInteriorNextStep(), quotedPrice.getInteriorTaskId(), OrderConstant.Auditing.DEFAULT);
            if (ResponseCode.SUCCESS.getCode() != taskResult.getCode()) {
                throw new RuntimeException(taskResult.getMessage());
            }
            if (purchaseInquiry.getOfferEndTime() <= System.currentTimeMillis()) {
                return Wrapper.fail("需求单的报价时间已截止，无法提交");
            }
            if (!purchaseInquiry.getTurn().equals(quotedPrice.getTurn())) {
                return Wrapper.fail("需求单(第" + purchaseInquiry.getTurn() + "轮)与单号为" + quotedPrice.getQuotedPriceNo() + "的报价单(第" + quotedPrice.getTurn() + "轮)的报价轮次不符合，无法提交");
            }

            quotedPrice.setInteriorTaskId(taskResult.getData().getTaskId());
            quotedPrice.setInteriorState(taskResult.getData().getStatus());
            quotedPrice.setInteriorNextStep(taskResult.getData().getStep());
            saveInteriorLog(sysUser, QuoteOperationEnum.SUBMIT_QUOTE.getCHName(), taskResult.getData().getStep(), taskResult.getData().getStatus(), quotedPrice.getId(), "");
            purchaseInquiry.setCount(null == purchaseInquiry.getCount() ? 1 : purchaseInquiry.getCount() + 1);
            list.add(purchaseInquiry);
            reduceCount(quotedPrice.getDetails(), quotedPrice.getCreateMemberId(), quotedPrice.getCreateMemberRoleId(), OperateDataSourceEnum.PURCHASE_QUOTED_PRICE.getCode(), 0L, 0, 1L, DemandQuotationOperateTypeEnum.TO_BE_COMMIT.getCode());
            reduceCount(quotedPrice.getDetails(), quotedPrice.getMemberId(), quotedPrice.getMemberRoleId(), OperateDataSourceEnum.PURCHASE_CONFIRM_QUOTED_PRICE.getCode(), 1L, ConfirmDemandQuotationOperateTypeEnum.TO_BE_VALIFY_COMMIT.getCode(), 0L, 0);
            sendSystemMessagePurchaseInquiry(purchaseInquiry, MessageTemplateCode.confirm_demand_quotation_wait_audit);
        }
        purchaseInquiryRepository.saveAll(list);
        quotedPriceRepository.saveAll(quotedPrices);

        //更新报价单当前轮次的状态为已完成
        List<QuotedPriceTurn> quotedPriceTurns = quotedPriceTurnRepository.findByQuotedPriceIdInAndTurn(
                quotedPrices.stream().map(QuotedPrice::getId).collect(Collectors.toList()),
                quotedPrices.get(0).getTurn()
        );
        if (CollectionUtil.isNotEmpty(quotedPriceTurns)) {
            List<QuotedPriceTurn> turnList = quotedPriceTurns.stream().peek(a -> a.setStatus(EnableDisableStatus.ENABLE.getCode())).collect(Collectors.toList());
            quotedPriceTurnRepository.saveAll(turnList);
        }

        return Wrapper.success();
    }

    /**
     * 采购合同-采购物料-分页查询
     */
    @Override
    public Wrapper<PageData<QuotedPriceProductResponse>> purchaseInquiryProductlistContract(ContractDetailsRequest request) {
        QuotedPrice quotedPrice = quotedPriceRepository.findByPurchaseInquiryIdAndCreateMemberIdAndCreateMemberRoleId(request.getId(), request.getMemberId(), request.getMemberRoleId());
        if (ObjectUtils.isEmpty(quotedPrice)) {
            return Wrapper.fail(ResponseCode.RECORDS_DON_T_EXIST);
        }
        Page<QuotedPriceDetails> quotedPriceDetailsPage = quotedPriceDetailsRepository.findAllByQuotedPriceIdAndIsPrize(quotedPrice.getId(), OrderConstant.State.START, PageRequest.of(request.getCurrent(), request.getPageSize(), Sort.by("id").descending()));
        List<QuotedPriceProductResponse> collect = quotedPriceDetailsPage.stream().map(temp -> {
            QuotedPriceProductResponse response = new QuotedPriceProductResponse();
            BeanUtils.copyProperties(temp, response);
            response.setId(temp.getId());
            //单价保留两位小数且四舍五入
            if (response.getTaxUnitPrice() != null) {
                response.setTaxUnitPrice(
                        BigDecimal.valueOf(response.getTaxUnitPrice()).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue()
                );
            }

            return response;
        }).collect(Collectors.toList());
        return Wrapper.success(new PageData<>(quotedPriceDetailsPage.getTotalElements(), collect));
    }

    /**
     * 平台后台报价列表查询
     */
    @Override
    public Wrapper<PageData<QuotedPriceListResponse>> platformQuotedPriceList(QuotedPriceListRequest request, UserLoginCacheDTO sysUser) {
        List<QuotedPriceListResponse> responses = new ArrayList<>();
        Specification<QuotedPrice> quotedPrice = (root, query, criteriaBuilder) -> {
            List<Predicate> predicates = new ArrayList<>();
            if (StringUtils.hasLength(request.getQuotedPriceNo())) {
                predicates.add(criteriaBuilder.like(root.get("quotedPriceNo"), "%" + request.getQuotedPriceNo() + "%"));
            }
            queryCondition(request.getMemberName(), request.getStartTime(), request.getEndTime(), request.getDetails(), request.getPurchaseInquiryNo(), predicates, criteriaBuilder, root);
            if (null != request.getExternalState()) {
                predicates.add(criteriaBuilder.equal(root.get("externalState"), request.getExternalState()));
            }
            if (null != request.getInteriorState()) {
                predicates.add(criteriaBuilder.equal(root.get("interiorState"), request.getInteriorState()));
            }
            Predicate[] predicate = new Predicate[predicates.size()];
            return criteriaBuilder.and(predicates.toArray(predicate));
        };
        Page<QuotedPrice> purchaseInquirys = quotedPriceRepository.findAll(quotedPrice, PageRequest.of(request.getCurrent(), request.getPageSize(), Sort.by("createTime").descending()));
        if (0 < purchaseInquirys.getTotalElements()) {
            responses = purchaseInquirys.getContent().stream().map(temp -> {
                QuotedPriceListResponse response = new QuotedPriceListResponse();
                response.setCreateTime(temp.getCreateTime());
                response.setPurchaseInquiryNo(temp.getPurchaseInquiryNo());
                response.setPurchaseInquiryId(temp.getPurchaseInquiryId());
                response.setOfferEndTime(temp.getOfferEndTime());
                response.setId(temp.getId());
                response.setMemberRoleId(temp.getMemberRoleId());
                response.setMemberName(temp.getMemberName());
                response.setMemberId(temp.getMemberId());
                response.setDeliveryTime(temp.getDeliveryTime());
                response.setExternalState(temp.getExternalState());
                response.setExternalStateName(PurchaseInquiryListExternalWorkStateEnum.getName(temp.getExternalState()));
                response.setInteriorState(temp.getInteriorState());
                response.setInteriorStateName(QuotedPriceInteriorWorkStateEnum.getName(temp.getInteriorState()));
                response.setDetails(temp.getDetails());
                response.setCreateTime(temp.getCreateTime());
                response.setTurn(temp.getTurn());
                response.setCount(temp.getCount());
                response.setQuotedPriceNo(temp.getQuotedPriceNo());
                return response;
            }).collect(Collectors.toList());
        }
        return Wrapper.success(new PageData<>(purchaseInquirys.getTotalElements(), responses));
    }

    /**
     * 平台后台报价单详情查询
     */
    @Override
    public Wrapper<QuotedPriceDetailsResponse> platformQuotedPriceDetails(BaseDetailsRequest request, UserLoginCacheDTO sysUser) {
        QuotedPrice quotedPrice;
        if (!StringUtils.hasLength(request.getNumber())) {
            quotedPrice = quotedPriceRepository.findById(request.getId()).orElse(null);
        } else {
            quotedPrice = quotedPriceRepository.findByQuotedPriceNo(request.getNumber());
        }
        if (ObjectUtils.isEmpty(quotedPrice)) {
            return Wrapper.fail(ResponseCode.RECORDS_DON_T_EXIST);
        }
        QuotedPriceDetailsResponse response = new QuotedPriceDetailsResponse();
        BeanUtils.copyProperties(quotedPrice, response);

        List<QuotedPriceDetails> quotedPriceDetailss = quotedPriceDetailsRepository.findAllByQuotedPriceId(quotedPrice.getId());
        response.setQuotedPriceProducts(intoQuotedPriceDetailsResponse(quotedPriceDetailss));

        //内外部状态name
        response.setExternalStateName(PurchaseInquiryListExternalWorkStateEnum.getName(quotedPrice.getExternalState()));
        response.setInteriorStateName(QuotedPriceInteriorWorkStateEnum.getName(quotedPrice.getInteriorState()));

        //查询内部流转状态
        response.setInteriorLogStates(getLogStateInterior(null, ProcessEnum.PURCHASE_INQUIRY_INNER_VERIFY.getCode(), quotedPrice.getInteriorNextStep()));
        //查询内部操作记录
        response.setInteriorLogs(getQuotedPriceInteriorLog(quotedPrice.getId()));
        //查询外部操作记录
        response.setExternalLogs(getExternalLog(quotedPrice.getPurchaseInquiryId()));
        //查询外部流转状态
        PurchaseInquiry purchaseInquiry = purchaseInquiryRepository.findById(quotedPrice.getPurchaseInquiryId()).orElse(null);
        response.setExternalLogStates(getLogStateResponse(ProcessEnum.PURCHASE_INQUIRY_OUTER_VERIFY.getCode(), quotedPrice.getExternalNextStep(), Collections.singletonList(quotedPrice.getCreateMemberRoleId()), purchaseInquiry.getCreateMemberRoleId()));
        response.setAreas(purchaseInquiry.getAreas().stream().map(temp -> {
            CountryAreaResponse countryArea = new CountryAreaResponse();
            BeanUtils.copyProperties(temp, countryArea);
            return countryArea;
        }).collect(Collectors.toList()));
        response.setIsAreas(OrderConstant.State.START.equals(purchaseInquiry.getIsAreas()));
        response.setAddress(purchaseInquiry.getAddress());
        response.setAddressId(purchaseInquiry.getAddressId());
        response.setOffer(purchaseInquiry.getOffer());
        response.setPaymentType(purchaseInquiry.getPaymentType());
        response.setTaxes(purchaseInquiry.getTaxes());
        response.setLogistics(purchaseInquiry.getLogistics());
        response.setPackRequire(purchaseInquiry.getPackRequire());
        response.setOtherRequire(purchaseInquiry.getOtherRequire());

        return Wrapper.success(response);
    }

    /**
     * 报价单详情-物料详情列表查询-分页
     */
    @Override
    public Wrapper<PageData<QuotedPriceProductResponse>> materielDetailed(MaterielDetailedRequest request, UserLoginCacheDTO sysUser) {
        QuotedPrice quotedPrice = quotedPriceRepository.findById(request.getId()).orElse(null);
        if (ObjectUtils.isEmpty(quotedPrice)) {
            return Wrapper.fail(ResponseCode.RECORDS_DON_T_EXIST);
        }
        Page<QuotedPriceDetails> page = quotedPriceDetailsRepository.findAllByQuotedPriceIdAndTurn(quotedPrice.getId(), request.getTurn(), PageRequest.of(request.getCurrent(), request.getPageSize(), Sort.by("id").ascending()));
        List<QuotedPriceProductResponse> lsit = new ArrayList<>();
        if (page.getTotalElements() > 0) {
            lsit = page.getContent().stream().map(temp -> {
                QuotedPriceProductResponse response = new QuotedPriceProductResponse();
                BeanUtils.copyProperties(temp, response);
                return response;
            }).collect(Collectors.toList());
        }
        return Wrapper.success(new PageData<>(page.getTotalElements(), lsit));
    }

    /**
     * 报价详情
     */
    @Override
    public Wrapper<ConfirmQuotedPriceResponse> platformDetails(ConfirmQuotedPriceDetailsRequest request, UserLoginCacheDTO sysUser) {
        ConfirmQuotedPriceResponse response = new ConfirmQuotedPriceResponse();
        PurchaseInquiry purchaseInquiry = purchaseInquiryRepository.findByIdAndCreateMemberIdAndCreateMemberRoleId(request.getId(), sysUser.getMemberId(), sysUser.getMemberRoleId());
        if (ObjectUtils.isEmpty(purchaseInquiry)) {
            return Wrapper.fail(ResponseCode.RECORDS_DON_T_EXIST);
        }
        BeanUtils.copyProperties(purchaseInquiry, response);
        response.setUrls(purchaseInquiry.getUrls());
        response.setTransactionUurls(purchaseInquiry.getTransactionUurls());
        response.setIsAreas(OrderConstant.State.START.equals(purchaseInquiry.getIsAreas()));
        response.setExternalStateName(PurchaseInquiryListExternalWorkStateEnum.getName(purchaseInquiry.getExternalState()));
        //查询内部操作记录
        response.setInteriorLogs(getInteriorLog(purchaseInquiry.getId()));
        //查询内部流转状态
        response.setInteriorLogStates(getLogStateInterior(null, ProcessEnum.PURCHASE_CONFIRM_OFFER_INNER_VERIFY.getCode(), purchaseInquiry.getConfirmInteriorNextStep()));
        //查询外部操作记录
        response.setExternalLogs(getExternalLog(purchaseInquiry.getId()));
        //查询外部流转状态
        List<Long> roles = getRolesByPurchaseInquiry(purchaseInquiry.getId());
        response.setExternalLogStates(getLogStateResponse(ProcessEnum.PURCHASE_INQUIRY_OUTER_VERIFY.getCode(), purchaseInquiry.getExternalNextStep(), roles, purchaseInquiry.getCreateMemberRoleId()));
        return Wrapper.success(response);
    }

    /**
     * 获取采购报价单内部流程状态
     */
    @Override
    public Wrapper<List<BiddingExternalWorkStateEnumResponse>> interiorStatus() {
        List<BiddingExternalWorkStateEnumResponse> collect = Arrays.stream(QuotedPriceInteriorWorkStateEnum.values()).map(temp -> {
            BiddingExternalWorkStateEnumResponse response = new BiddingExternalWorkStateEnumResponse();
            response.setName(temp.getName());
            response.setSatatus(temp.getState());
            return response;
        }).collect(Collectors.toList());
        return Wrapper.success(collect);
    }


    /**
     * 采购报价-采购报价单查询
     */
    public Wrapper<PageData<QuotedPriceListResponse>> getQuotedPriceList(QuotedPriceListRequest request, UserLoginCacheDTO sysUser, Integer queryType) {
        List<QuotedPriceListResponse> responses = new ArrayList<>();
        Specification<QuotedPrice> quotedPrice = (root, query, criteriaBuilder) -> {
            List<Predicate> predicates = new ArrayList<>();
            predicates.add(criteriaBuilder.equal(root.get("createMemberId"), sysUser.getMemberId()));
            predicates.add(criteriaBuilder.equal(root.get("createMemberRoleId"), sysUser.getMemberRoleId()));
            if (StringUtils.hasLength(request.getQuotedPriceNo())) {
                predicates.add(criteriaBuilder.like(root.get("quotedPriceNo"), "%" + request.getQuotedPriceNo() + "%"));
            }
            queryCondition(request.getMemberName(), request.getStartTime(), request.getEndTime(), request.getDetails(), request.getPurchaseInquiryNo(), predicates, criteriaBuilder, root);
            if (QuotedPriceQueryEnum.PURCHASE_INQUIRY_LIST.getType().equals(queryType)) {
                if (null != request.getExternalState()) {
                    predicates.add(criteriaBuilder.equal(root.get("externalState"), request.getExternalState()));
                }
                if (null != request.getInteriorState()) {
                    predicates.add(criteriaBuilder.equal(root.get("interiorState"), request.getInteriorState()));
                }
            } else if (QuotedPriceQueryEnum.ADD_PURCHASE_INQUIRY_LIST.getType().equals(queryType)) {
                predicates.add(
                        criteriaBuilder.or(criteriaBuilder.equal(root.get("interiorState"), QuotedPriceInteriorWorkStateEnum.STAY_SUBMIT_EXAMINE.getState()),
                                criteriaBuilder.equal(root.get("interiorState"), QuotedPriceInteriorWorkStateEnum.EXAMINE_NOT_ADOPT1.getState()),
                                criteriaBuilder.equal(root.get("interiorState"), QuotedPriceInteriorWorkStateEnum.EXAMINE_NOT_ADOPT2.getState()))
                );
            } else if (QuotedPriceQueryEnum.EXAMINE_PURCHASE_INQUIRY_LIST1.getType().equals(queryType)) {
                predicates.add(criteriaBuilder.equal(root.get("interiorState"), QuotedPriceInteriorWorkStateEnum.STAY_EXAMINE1.getState()));
            } else if (QuotedPriceQueryEnum.EXAMINE_PURCHASE_INQUIRY_LIST2.getType().equals(queryType)) {
                predicates.add(criteriaBuilder.equal(root.get("interiorState"), QuotedPriceInteriorWorkStateEnum.STAY_EXAMINE2.getState()));
            } else if (QuotedPriceQueryEnum.SUBMIT_PURCHASE_INQUIRY_LIST.getType().equals(queryType)) {
                predicates.add(criteriaBuilder.equal(root.get("interiorState"), QuotedPriceInteriorWorkStateEnum.STAY_SUBMIT_EXAMINE_QUOTEDPRICE.getState()));
            }
            Predicate[] predicate = new Predicate[predicates.size()];
            return criteriaBuilder.and(predicates.toArray(predicate));
        };
        Page<QuotedPrice> quotedPrices = quotedPriceRepository.findAll(quotedPrice, PageRequest.of(request.getCurrent(), request.getPageSize(), Sort.by("createTime").descending()));
        if (0 < quotedPrices.getTotalElements()) {
            //获取全部需求单号
            List<Long> purchaseInquiryIds = quotedPrices.getContent().stream().map(QuotedPrice::getPurchaseInquiryId).collect(Collectors.toList());
            //根据单号获取需求单外部状态
            List<PurchaseInquiry> inquiryList = purchaseInquiryRepository.findAllById(purchaseInquiryIds);
            //封装数据(key:需求单id,value:需求单externalState)
            Map<Long, Integer> inquiryMap = inquiryList.stream().collect(Collectors.toMap(PurchaseInquiry::getId, PurchaseInquiry::getExternalState));
            responses = quotedPrices.getContent().stream().map(temp -> {
                QuotedPriceListResponse response = new QuotedPriceListResponse();
                response.setCreateTime(temp.getCreateTime());
                response.setPurchaseInquiryNo(temp.getPurchaseInquiryNo());
                response.setPurchaseInquiryId(temp.getPurchaseInquiryId());
                response.setOfferEndTime(temp.getOfferEndTime());
                response.setId(temp.getId());
                response.setMemberRoleId(temp.getMemberRoleId());
                response.setMemberName(temp.getMemberName());
                response.setMemberId(temp.getMemberId());
                response.setExternalState(inquiryMap.get(temp.getPurchaseInquiryId()));
                response.setExternalStateName(PurchaseInquiryListExternalWorkStateEnum.getName(inquiryMap.get(temp.getPurchaseInquiryId())));
                response.setInteriorState(temp.getInteriorState());
                response.setInteriorStateName(QuotedPriceInteriorWorkStateEnum.getName(temp.getInteriorState()));
                response.setDetails(temp.getQuotedDetails());
                response.setCreateTime(temp.getCreateTime());
                response.setTurn(temp.getTurn());
                response.setCount(temp.getCount());
                response.setQuotedPriceNo(temp.getQuotedPriceNo());
                Boolean isPrize = (temp.getIsPrize() == null || temp.getIsPrize() == 0) ? Boolean.FALSE : Boolean.TRUE;
                response.setIsPrize(isPrize);
                return response;
            }).collect(Collectors.toList());
        }
        return Wrapper.success(new PageData<>(quotedPrices.getTotalElements(), responses));
    }

    /**
     * 记录采购询价单内部操作记录
     */
    public void saveInteriorLog(UserLoginCacheDTO sysUser, String operation, Integer step, Integer state, Long id, String auditOpinion) {
        //记录操作记录
        InteriorQuotedPriceLog interiorLog = new InteriorQuotedPriceLog();
        interiorLog.setRoleName(sysUser.getUserName());
        interiorLog.setDepartment(sysUser.getUserOrgName());
        interiorLog.setPosition(sysUser.getUserJobTitle());
        interiorLog.setQuotedPriceId(id);
        interiorLog.setState(state);
        interiorLog.setStep(step);
        interiorLog.setOperation(operation);
        interiorLog.setAuditOpinion(auditOpinion);
        interiorLog.setCreateTime(System.currentTimeMillis());
        interiorLog.setCreateRoleId(sysUser.getMemberRoleId());
        interiorLog.setCreateMemberId(sysUser.getMemberId());
        interiorQuotedPriceLogRepository.saveAndFlush(interiorLog);
    }



    /**
     * 报价单详情查询
     */
    private List<QuotedPriceProductResponse> intoQuotedPriceDetailsResponse(List<QuotedPriceDetails> quotedPriceDetailss) {
        return quotedPriceDetailss.stream().map(temp -> {
            QuotedPriceProductResponse response = new QuotedPriceProductResponse();
            BeanUtils.copyProperties(temp, response);
            return response;
        }).collect(Collectors.toList());
    }

    /**
     * 查询采购报价单外部操作记录
     */
    public List<InteriorPurchaseInquiryLogResponse> getQuotedPriceInteriorLog(Long quotedPriceId) {
        List<InteriorQuotedPriceLog> interiorQuotedPriceLogs = interiorQuotedPriceLogRepository.findAllByQuotedPriceId(quotedPriceId);
        if (CollectionUtils.isEmpty(interiorQuotedPriceLogs)) {
            return new ArrayList<>();
        }
        return interiorQuotedPriceLogs.stream().map(temp -> {
            InteriorPurchaseInquiryLogResponse logResponse = new InteriorPurchaseInquiryLogResponse();
            BeanUtils.copyProperties(temp, logResponse);
            logResponse.setStateName(QuotedPriceInteriorWorkStateEnum.getName(temp.getState()));
            logResponse.setOperation(QuoteOperationEnum.getName(temp.getOperation()));
            logResponse.setAuditOpinion(StatusEnum.AGREE.getCHName().equals(temp.getAuditOpinion()) ? StatusEnum.getName(temp.getAuditOpinion()) : temp.getAuditOpinion());
            return logResponse;
        }).collect(Collectors.toList());
    }


    /**
     * 发消息
     */
    @Async
    public void sendSystemMessage(QuotedPrice quotedPrice, String name) {
        try {
            SystemMessageRequest systemMessageRequest = new SystemMessageRequest();
            systemMessageRequest.setMemberId(quotedPrice.getCreateMemberId());
            systemMessageRequest.setRoleId(quotedPrice.getCreateMemberRoleId());
            systemMessageRequest.setMessageNotice(name);
            systemMessageRequest.setParams(Arrays.asList(quotedPrice.getQuotedPriceNo(), quotedPrice.getQuotedDetails()));
            systemMessageControllerFeign.sendSystemMessage(systemMessageRequest);
        } catch (Exception e) {
            log.error("发送采购报价单通知消息异常", e);
        }
    }
}
